const express=require("express");
const handleDB=require("../db/handleDB");
require("../utils/filter");
const common=require("../utils/common");
const constant=require("../utils/constant");


const router=express.Router();

router.get("/news_detail/:news_id",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res)

        let result3=await handleDB(res,"info_news","find","查询数据库出错","1 order by clicks desc limit 6")

        let {news_id}=req.params;

        let newsResult=await handleDB(res,"info_news","find","查询数据库出错",`id=${news_id}`)

        if(!newsResult[0]){
            common.abort404(req,res);
            return
        }

        newsResult[0].clicks+=1
        await handleDB(res,"info_news","update","数据库更新出错",`id=${news_id}`,{clicks:newsResult[0].clicks})

        let isCollected=false;
        if(userInfo[0]){
            let collectionResult=await handleDB(res,"info_user_collection","find","查询数据库出错",`user_id=${userInfo[0].id} and news_id=${news_id}`)
            if(collectionResult[0]){
                isCollected=true;
            }
        }

        let commentResult=await handleDB(res,"info_comment","find","查询数据库出错",`news_id=${news_id} order by create_time desc`)


        for(let i=0;i<commentResult.length;i++){
            let commenterResult=await handleDB(res,"info_user","find","查询数据库出错",`id=${commentResult[i].user_id}`)

            commentResult[i].commenter={
                nick_name:commenterResult[0].nick_name,
                avatar_url:commenterResult[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE+commenterResult[0].avatar_url):"/news/images/worm.jpg"
            }

            if(commentResult[i].parent_id){
                var parentComment=await handleDB(res,"info_comment","find","数据库查询失败",`id=${commentResult[i].parent_id}`)
                var parentUserInfo=await handleDB(res,"info_user","find","数据库查询失败",`id=${parentComment[0].user_id}`)

                commentResult[i].parent={
                    user:{
                        nick_name:parentUserInfo[0].nick_name
                    },
                    content:parentComment[0].content
                }
            }
        }

        let user_like_comments_ids=[];
        if(userInfo[0]){
            let user_like_commentsResult=await handleDB(res,"info_comment_like","find","数据库查询出错",`user_id=${userInfo[0].id}`)

            user_like_commentsResult.forEach(el=>{
                user_like_comments_ids.push(el.comment_id)
            })
        }

        let authorInfo=await handleDB(res,"info_user","find","数据库查询出错",`id=${newsResult[0].user_id}`);

        let authorNewsCount=await handleDB(res,"info_news","sql","数据库查询出错",`select count(*) from info_news where user_id=${authorInfo[0].id}`)

        let authorFansCount=await handleDB(res,"info_user_fans","sql","数据库查询出错",`select count(*) from info_user_fans where followed_id=${authorInfo[0].id}`)

        let isFollow=false;
        if(userInfo[0]){
            let followResult=await handleDB(res,"info_user_fans","find","查询数据库出错",`follower_id=${userInfo[0].id} and followed_id=${authorInfo[0].id}`)
            if(followResult[0]){
                isFollow=true;
            }
        }

        authorInfo[0].avatar_url=authorInfo[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE+authorInfo[0].avatar_url):"/news/images/worm.jpg"

        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                avatar_url:userInfo[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE+userInfo[0].avatar_url):"/news/images/worm.jpg"
            }:false,
            newsClick:result3,
            newsData:newsResult[0],
            isCollected,
            commentList:commentResult,
            user_like_comments_ids,
            authorInfo:authorInfo[0],
            authorNewsCount:authorNewsCount[0]["count(*)"],
            authorFansCount:authorFansCount[0]["count(*)"],
            isFollow
        }
        res.render("news/detail",data);
})();
})

router.post("/news_detail/news_collect",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {news_id,action}=req.body;
        if(!news_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        let newsResult=await handleDB(res,"info_news","find","数据库查询出错",`id=${news_id}`);
        if(!newsResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="collect"){
            await handleDB(res,"info_user_collection","insert","数据库添加失败",{
                user_id:userInfo[0].id,
                news_id
            })
        }else{
            await handleDB(res,"info_user_collection","delete","数据库删除失败",`user_id=${userInfo[0].id} and news_id=${news_id}`)
        }
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})

router.post("/news_detail/news_comment",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {news_id,comment,parent_id=null}=req.body;
        if(!news_id || !comment){
            res.send({errmsg:"参数错误1"})
            return
        }

        let newsResult=await handleDB(res,"info_news","find","数据库查询出错",`id=${news_id}`)
        if(!newsResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        let commentObj={
            user_id:userInfo[0].id,
            news_id,
            content:comment,
            create_time:new Date().toLocaleString('chinese',{hour12:false})
        }
        if(parent_id){
            commentObj.parent_id=parent_id

            var parentComment=await handleDB(res,"info_comment","find","数据库查询出错",`id=${parent_id}`)

            var parentUserInfo=await handleDB(res,"info_user","find","数据库查询失败",`id=${parentComment[0].user_id}`)
        }

        let insertResult=await handleDB(res,"info_comment","insert","数据库插入失败",commentObj);

        let data={
            user:{
                avatar_url:userInfo[0].avatar_url?userInfo[0].avatar_url:"/news/images/worm.jpg",
                nick_name:userInfo[0].nick_name
            },
            content:comment,
            create_time:commentObj.create_time,
            news_id,
            id:insertResult.insertId,
            parent:parent_id?{
                user:{
                    nick_name:parentUserInfo[0].nick_name
                },
                content:parentComment[0].content
            }:null
        }
        res.send({errno:'0',errmsg:"操作成功",data})
        
    })();
})

router.post("/news_detail/comment_like",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {comment_id,action}=req.body;
        if(!comment_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        let commentResult=await handleDB(res,"info_comment","find","数据库查询出错",`id=${comment_id}`)
        if(!commentResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="add"){
            await handleDB(res,"info_comment_like","insert","数据库添加出错",{
                comment_id,
                user_id:userInfo[0].id
            })
            var like_count=commentResult[0].like_count?commentResult[0].like_count+1:1
        }else{
            await handleDB(res,"info_comment_like","delete","数据库删除出错",`comment_id=${comment_id} and user_id=${userInfo[0].id}`)
            var like_count=commentResult[0].like_count?commentResult[0].like_count-1:0
        }

        await handleDB(res,"info_comment","update","数据库更新失败",`id=${comment_id}`,{like_count})

        res.send({errno:"0",errmsg:"操作成功"})
        
    })();
})

router.post("/news_detail/followed_user",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {user_id,action}=req.body;
        if(!user_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        if(user_id==userInfo[0].id){
            res.send({errmsg:"用户自己不能关注自己的文章"})
            return
        }
        let userResult=await handleDB(res,"info_user","find","数据库查询出错",`id=${user_id}`);
        if(!userResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="follow"){
            await handleDB(res,"info_user_fans","insert","数据库添加失败",{
                follower_id:userInfo[0].id,
                followed_id:user_id
            })
        }else{
            await handleDB(res,"info_user_fans","delete","数据库删除失败",`follower_id=${userInfo[0].id} and followed_id=${user_id}`)
        }
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})
module.exports=router